#!/usr/bin/env python3
"""
新浪财经数据源实现
基于新浪财经API的免费A股数据获取
"""

import pandas as pd
import requests
from datetime import datetime, timedelta
from typing import Dict, Any, Optional
import time
import json

from .base import BaseDataSource, DataSourceStatus
from ..utils.logger import get_logger

logger = get_logger("SinaSource")


class SinaSource(BaseDataSource):
    """新浪财经数据源"""

    def __init__(self, config: Dict[str, Any] = None):
        super().__init__("sina", config)
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        })
        self._initialize_fetcher()

    def _initialize_fetcher(self):
        """初始化数据获取器"""
        try:
            self.update_status(DataSourceStatus.AVAILABLE)
            logger.info("新浪财经数据源初始化成功")
        except Exception as e:
            self.update_status(DataSourceStatus.ERROR, str(e))
            logger.error(f"新浪财经数据源初始化失败: {e}")

    def check_availability(self) -> bool:
        """检查数据源是否可用"""
        try:
            # 简单检查，不进行网络请求
            available = self.session is not None
            self.update_status(
                DataSourceStatus.AVAILABLE if available else DataSourceStatus.ERROR,
                None if available else "新浪财经未可用"
            )
            return available
        except Exception as e:
            self.update_status(DataSourceStatus.ERROR, str(e))
            return False

    def get_stock_list(self) -> pd.DataFrame:
        """获取股票列表"""
        try:
            # 新浪财经没有直接的股票列表API，这里返回一个基础的A股列表
            # 实际应用中可以从其他数据源获取列表，然后用新浪获取实时数据
            logger.warning("新浪财经不提供完整的股票列表API，建议与其他数据源配合使用")
            return pd.DataFrame()
        except Exception as e:
            logger.error(f"新浪财经获取股票列表失败: {e}")
            return pd.DataFrame()

    def fetch_history_data(self, symbol: str, interval: str,
                          start_date: str, end_date: str) -> pd.DataFrame:
        """获取历史数据"""
        try:
            # 新浪财经的历史数据API
            market = 'sh' if symbol.startswith('6') else 'sz'
            
            # 构建URL
            url = f"http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData"
            params = {
                'symbol': f"{market}{symbol}",
                'scale': self._convert_interval(interval),
                'ma': 'no',
                'datalen': 1000  # 最大数据量
            }
            
            response = self.session.get(url, params=params, timeout=30)
            if response.status_code == 200:
                data = response.text
                # 清理数据格式
                data = data.replace('null', '""')
                try:
                    json_data = json.loads(data)
                    if json_data:
                        df = pd.DataFrame(json_data)
                        
                        # 转换为统一格式
                        df = df.rename(columns={
                            'day': 'Date',
                            'open': 'Open',
                            'high': 'High',
                            'low': 'Low',
                            'close': 'Close',
                            'volume': 'Volume'
                        })
                        
                        # 数据类型转换
                        df['Date'] = pd.to_datetime(df['Date'])
                        for col in ['Open', 'High', 'Low', 'Close', 'Volume']:
                            df[col] = pd.to_numeric(df[col], errors='coerce')
                        
                        # 过滤日期范围
                        start_dt = pd.to_datetime(start_date)
                        end_dt = pd.to_datetime(end_date)
                        df = df[(df['Date'] >= start_dt) & (df['Date'] <= end_dt)]
                        
                        df = df[['Date', 'Open', 'High', 'Low', 'Close', 'Volume']].sort_values('Date')
                        
                        # 添加延迟避免频率限制
                        time.sleep(0.2)
                        
                        return df
                except json.JSONDecodeError:
                    logger.error(f"新浪财经数据解析失败: {symbol}")
                    
            return pd.DataFrame()

        except Exception as e:
            logger.error(f"新浪财经获取历史数据失败 {symbol}: {e}")
            return pd.DataFrame()

    def _convert_interval(self, interval: str) -> str:
        """转换时间间隔格式"""
        interval_map = {
            '5m': '5',
            '15m': '15', 
            '30m': '30',
            '1h': '60',
            '1d': '240'  # 日线
        }
        return interval_map.get(interval, '240')

    def get_stock_info(self, symbol: str) -> Dict[str, Any]:
        """获取股票信息"""
        try:
            # 获取股票实时信息
            market = 'sh' if symbol.startswith('6') else 'sz'
            url = f"http://hq.sinajs.cn/list={market}{symbol}"
            
            response = self.session.get(url, timeout=10)
            if response.status_code == 200:
                content = response.text
                if 'var hq_str_' in content:
                    # 解析数据
                    data_str = content.split('"')[1]
                    data_parts = data_str.split(',')
                    
                    if len(data_parts) > 1:
                        return {
                            'symbol': symbol,
                            'name': data_parts[0],
                            'market': market.upper()
                        }
            
            return {}
        except Exception as e:
            logger.error(f"新浪财经获取股票信息失败 {symbol}: {e}")
            return {}
